# https://www.youtube.com/watch?v=ywaSiIf1C2w&t=64s
from flask import Flask
from flask import render_template
from flask import Response
import cv2
app = Flask(__name__)
#实例化相机
camdevice = cv2.VideoCapture(0)
#设置相机分辨率
camdevice.set(cv2.CAP_PROP_FRAME_WIDTH,640)
camdevice.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
face_cascade = cv2.CascadeClassifier(r"C:\Users\56526\AppData\Local\Programs\Python\Python313\Lib\site-packages\cv2\data\haarcascade_frontalface_alt.xml")
def generate():
    while True:
        ret,img = camdevice.read()#采集图片
        if not ret or img is None:
            continue
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#彩色图片转灰度图
        faces = face_cascade.detectMultiScale(gray,1.1,4)#检测人脸
        for (x,y,w,h) in faces:
            cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),1)
        #这是在进行图片的编码
        flag,encodedImage = cv2.imencode(".jpg",img)
        if not flag:
            continue
        yield(b'--img\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')
@app.route("/")
def index():
    return render_template("index.html")

@app.route("/video_feed")
def video_feed():
    return Response(generate(),mimetype = "multipart/x-mixed-replace; boundary=img")
if __name__ == "__main__":
    app.run(debug=True)